<template>
  <el-card shadow="never"
           style="padding:20px"
           class="aui-card--fill record-content">
    <div class="search-area">
      <el-row style="margin-bottom:10px;">
        <el-col :span="6">
          <el-date-picker v-model="searchForm.logDateModel"
                          type="daterange"
                          size="small"
                          @change="dateChange"
                          range-separator="-"
                          clearable
                          value-format="yyyy-MM-dd"
                          style="width:100%;"
                          :start-placeholder="$t('datePicker.start')"
                          :end-placeholder="$t('datePicker.end')"></el-date-picker>
        </el-col>
        <el-col :span="3"
                style="margin-left:20px">
          <el-select v-model="searchForm.teamId"
                     filterable
                     @change="teamChange"
                     clearable
                     size="small"
                     :placeholder="$t('custom.attendance.record.search.team')">
            <el-option v-for="(item,ii) in teamList"
                       :key="ii"
                       :label="item.teamName"
                       :value="item.teamId">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4"
                style="margin-left:20px">
          <el-select v-model="searchForm.userIds"
                     @visible-change="userChange"
                     filterable
                     multiple
                     @remove-tag="userItemChange"
                     @clear="clearItem"
                     size="small"
                     collapse-tags
                     clearable
                     class="multiple-select--collapse"
                     :placeholder="$t('custom.attendance.record.search.member')">
            <template v-if="searchForm.teamId">
              <div>
                <el-button @click="searchForm.userIds.length===userLists.filter(i=>i.teamId===searchForm.teamId).length?searchForm.userIds=[]:selectAll(userLists.filter(i=>i.teamId===searchForm.teamId))"
                           type="text"
                           size="mini"
                           style="width:100%;text-align:center;font-size:14px">{{searchForm.userIds.length===userLists.filter(i=>i.teamId===searchForm.teamId).length?$t('custom.attendance.record.search.clearall'):$t('custom.attendance.record.search.selectall')}}</el-button>
              </div>
              <el-option v-for="(item,ii) in userLists.filter(i=>i.teamId===searchForm.teamId)"
                         :key="ii"
                         :label="item.realName"
                         :value="item.memberId">
              </el-option>
            </template>
            <template v-else>
              <div>
                <el-button @click="searchForm.userIds.length===userLists.length?searchForm.userIds=[]:selectAll(userLists)"
                           type="text"
                           size="mini"
                           style="width:100%;text-align:center;font-size:14px">{{searchForm.userIds.length===userLists.length?$t('custom.attendance.record.search.clearall'):$t('custom.attendance.record.search.selectall')}}</el-button>
              </div>
              <el-option v-for="(item,ii) in userLists"
                         :key="ii"
                         :label="item.realName"
                         :value="item.memberId">
              </el-option>
            </template>
          </el-select>
        </el-col>
        <!-- <span style="margin-left:20px;float:right" >
          <el-button v-loading="generateLoading" @click="openDialog" type="primary" size="small">{{$t('custom.attendance.record.search.generate')}}</el-button>
        </span> -->
      </el-row>
    </div>
    <ejs-grid :dataSource="comDataList"
                  :rowDataBound='rowDataBound'
                  :groupSettings='groupOptions'
                  style="height:calc(100% - 85px);overflow: auto;"
                  v-loading="dataListLoading"
                  :element-loading-text="$t('loading')"
                  element-loading-spinner="el-icon-loading"
                  element-loading-background="rgba(255, 255, 255, 0.8)"
                  :allowResizing="gridDefaultSetting.allowResizing"
                  :allowFiltering="false"
                  :filterSettings="gridDefaultSetting.filterSettings"
                  :allowGrouping="gridDefaultSetting.allowGrouping"
                  :allowPaging="false"
                  :toolbar="toolbar"
                  :allowExcelExport='true'
                  :allowPdfExport='true'
                  :allowTextWrap="gridDefaultSetting.allowTextWrap"
                  :showColumnChooser="gridDefaultSetting.showColumnChooser"
                  :allowReordering="gridDefaultSetting.allowReordering"
                  :allowSorting="gridDefaultSetting.allowSorting"
                  :editSettings="gridDefaultSetting.editSettings"
                  ref="grid"
                  :toolbarClick='toolbarClick'
                  :selectionSettings="gridDefaultSetting.selectOptions"
                  :commandClick="commandClick"
                  :rowSelected="dataListSelectionChangeHandle">
          <e-columns>
            <!-- <e-column type='checkbox'
                      :allowFiltering='false'
                      :allowSorting='false'
                      width='40'></e-column> -->
            <e-column field='team'
                      width='110'
                      :headerText="$t('custom.attendance.record.tableTitle.team')"></e-column>
            <e-column field='username'
                      width='110'
                      :headerText="$t('custom.attendance.record.tableTitle.member')"></e-column>
            <e-column field='action'
                      alignText='center'
                      width='130'
                      :template='actionTemplate'
                      :headerText="$t('custom.attendance.record.tableTitle.action')"></e-column>
            <e-column field='logTime'
                      width='180'
                      :template='logTimeTemplate'
                      :headerText="$t('custom.attendance.record.tableTitle.timeStamp')"></e-column>
            <e-column field='approveTime'
                      width='180'
                      :template='approveTimeTemplate'
                      :headerText="$t('custom.attendance.record.tableTitle.approveTime')"></e-column>
            <e-column field='duration'
                      width='170'
                      :template='durationTemplate'
                      :headerText="$t('custom.attendance.record.tableTitle.duration')"></e-column>
            <e-column field='status'
                      width='160'
                      :headerText="$t('custom.attendance.record.tableTitle.status')"></e-column>
            <e-column field='comments'
                      width='110'
                      :headerText="$t('custom.attendance.record.tableTitle.comments')"></e-column>
            <!-- <e-column field='workSchedule.FRIDAY'
                      width='110'
                      :headerText="$t('custom.workSchedule.listTitle.friday')"></e-column>
            <e-column field='workSchedule.SATURDAY'
                      width='110'
                      :headerText="$t('custom.workSchedule.listTitle.saturday')"></e-column>
            <e-column field='workSchedule.SUNDAY'
                      width='110'
                      :headerText="$t('custom.workSchedule.listTitle.sunday')"></e-column> -->
            <e-column :template='handleTemplate'
                      width='110'
                      :dict="dict"
                      :adminUserId="adminUserId"
                      :headerText="$t('custom.attendance.record.tableTitle.approval')"
                      textAlign="center"></e-column>
          </e-columns>
        </ejs-grid>
        <el-pagination background
                       layout="total, sizes, prev, pager, next, jumper"
                       @current-change="pageCurrentChangeHandle"
                       @size-change="pageSizeChangeHandle"
                       :page-sizes="[20, 50, 100, 200, 1000]"
                       :pager-count="$store.state.app.pageOptions.pageCount"
                       :current-page="pageOptions.currentPage"
                       :total="pageOptions.total">
        </el-pagination>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :mappingForm="mappingFormSetting"
           :updateGadget="upgradeGadgetSetting" />
  </el-card>
</template>

<script>
import { generalConvertJsonToSQL ,GlobalTimeformat } from '@/utils/common'
import moment from 'moment'
import { BridgeComponentForAttendance } from './BridgeComponentForAttendance'
import actionTemplate from './record-template/action-template'
import LogTimeTemplate from '@/components/grid-format/LogTimeformat'
import ApproveTimeTemplate from './record-template/log-time-updated'
import HandleTemplate from './record-template/handle-template'
import DurationTemplate from './record-template/duration-template'
import thisStore from '@/store'
import {
  fetchWorkScheduledUser,
} from '@/api/new'
import config from '@/utils/config'

import mixinViewModule from '@/mixins/crud-view-modul-plus'

export default {
  components: {
    model: () => import('@/components/gadget/query-model/query-model')
  },
  mixins: [mixinViewModule],
  data () {
    return {
      actionTemplate: function () {
        return { template: actionTemplate }
      },
      logTimeTemplate: function () {
        return { template: LogTimeTemplate }
      },
      approveTimeTemplate: function () {
        return { template: ApproveTimeTemplate }
      },
      handleTemplate: function () {
        return { template: HandleTemplate }
      },
      durationTemplate: function () {
        return { template: DurationTemplate }
      },
      height: window.innerHeight - 395,
      groupOptions: { columns: [] },
      filterSettings: { type: 'Excel' },
      toolbar: ['PdfExport', 'CsvExport', 'ColumnChooser'],
      dataList: [],
      dict: {},
      adminUserId:"",
      dataForm: {
        createTimeStart: null,
        createTimeEnd: null,
        tenantCode: this.$store.state.user.tenantCode,
        userIds: [],
        logTimeStart: null,
        logTimeEnd: null,
        team: null
      },
      mixinViewModuleOptions: {
        getDataListURL: '/web/attendance/attendance/findByParam',
        getDataListIsPage: true
      },
      size: 20,
      userLists: [],
      searchForm: {
        teamId: null,
        userIds: [],
        logDateModel: []
      },
      teamList: [],
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: '',
          gadgetId: '',
          gadgetType: '',
          gadgetSetting: {},
          reuse: true
        }
      },
      generateLoading: false
    }
  },
  mounted () {
    // this.getRecordLists()
    BridgeComponentForAttendance.$on('initRecordList', () => {
      // this.getRecordLists()
      this.query()
      this.getFormData()
    })
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.getTeamList()
    this.getFormData()
    this.getAdminUser()
  },
  computed: {
    comDataList () {
      this.dataList.forEach(item => {
        if (item.subAction) {
          // eslint-disable-next-line
          item.action = item.subAction
        }
      })
      return this.dataList
    }
  },
  methods: {
    toolbarClick (args) {
      var excelExportProperties = {}
      var formatDataList = []
      if(this.dataList.length === 0) {
        return
      }
      formatDataList = this.dataList.forEach(item => {
        if (item.logTime) {
          item.logTime = GlobalTimeformat(item.logTime, 'HH:mm')
        }
        if (item.logTimeUpdated) {
          item.approveTime = GlobalTimeformat(item.logTimeUpdated, 'HH:mm')
        }
        if (item.duration) {
          item.duration = this.durationformat(item.duration)
        }
      })
      switch (args.item.text) {
        case 'PDF Export':
            this.$refs.grid.pdfExport(excelExportProperties)          
          break
        case 'Excel Export':       
          excelExportProperties = {
            dataSource: formatDataList
          }
          this.$refs['grid'].excelExport(excelExportProperties)
          break
        case 'CSV Export':
          excelExportProperties = {
            dataSource: formatDataList
          }
          this.$refs['grid'].csvExport(excelExportProperties)
          break
      }
    },
    durationformat (item) {
      if (item) {
        let tempTime = moment.duration(item, 'seconds')
        let time = ''
        if (tempTime.asHours() > 0) {
          time += parseInt(tempTime.asHours()) + ':'
        }
        if (tempTime.minutes() > 0) {
          if (tempTime.minutes() < 10) {
            time += '0' + tempTime.minutes()
          } else {
            time += tempTime.minutes()
          }
        }
        if (tempTime.minutes() < 1) {
          time += '00'
        }
        return time
      }
    },
    selectAll (arr) {
      this.searchForm.userIds = []
      arr.forEach(item => {
        this.searchForm.userIds.push(item.memberId)
      })
    },
    upgradeGadgetSetting () {

    },
    mappingFormSetting (to, from) {

    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    queryModelClosed () {
      this.$store.state.isAttendanceSummaryWidget = false
      this.queryModelDefaultSetting.showSetting = false
      // if (this.viewValue === 'List') {
      //   this.$refs.ListWidgets.cardQuery()
      // } else {
      //   this.query()
      // }
    },
    openDialog () {
      var userIds = []
      if (this.searchForm.userIds) {
        userIds = JSON.parse(JSON.stringify(this.searchForm.userIds))
        if (Array.isArray(userIds)) {
          userIds = userIds.map(item => {
            var res = this.userLists.find(i => i.memberId === item)
            if (res) {
              return res.realName
            } else {
              return ''
            }
          })
        }
      }
      var filterJson = {
        'rules': [
        ],
        'condition': 'and'
      }
      if (this.searchForm.teamId) {
        var res = this.teamList.find(i => i.teamId === this.searchForm.teamId)
        if (res) {
          filterJson.rules.push({
            'key': 'Team',
            'opt': 'ilike',
            'type': 'text',
            'value': res.teamName,
            'slicer': {
              'id': '',
              'dbType': '',
              'status': false,
              'slicerKey': [

              ],
              'slicerName': '',
              'ignoreFilter': false,
              'currentSlicer': '',
              'currentSlicerStatus': false
            }
          })
        }
      }
      if (Array.isArray(this.searchForm.logDateModel) && this.searchForm.logDateModel[0]) {
        filterJson.rules.push({
          'key': 'date',
          'opt': '>=',
          'type': 'date',
          'value': this.searchForm.logDateModel[0],
          'slicer': {
            'id': '',
            'dbType': '',
            'status': false,
            'slicerKey': [

            ],
            'slicerName': '',
            'ignoreFilter': false,
            'currentSlicer': '',
            'currentSlicerStatus': false
          }
        })
      }
      if (Array.isArray(this.searchForm.logDateModel) && this.searchForm.logDateModel[1]) {
        filterJson.rules.push({
          'key': 'date',
          'opt': '<=',
          'type': 'date',
          'value': this.searchForm.logDateModel[1],
          'slicer': {
            'id': '',
            'dbType': '',
            'status': false,
            'slicerKey': [

            ],
            'slicerName': '',
            'ignoreFilter': false,
            'currentSlicer': '',
            'currentSlicerStatus': false
          }
        })
      }
      if (userIds.length > 0) {
        filterJson.rules.push({
          'key': 'Member Full Name',
          'opt': 'in',
          'type': 'text',
          'value': userIds,
          'slicer': {
            'id': '',
            'dbType': '',
            'status': false,
            'slicerKey': [

            ],
            'slicerName': '',
            'ignoreFilter': false,
            'currentSlicer': '',
            'currentSlicerStatus': false
          }
        })
      }
      const gadgetId = '77b1c4f9-540a-42a9-80f7-7754ff815c25' // for attendance's widget
      const _self = this
      const params = {
        gadgetId: gadgetId
      }
      _self.generateLoading = true
      _self.$interface.reports.getFilterDetailApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            _self.generateLoading = false
            return _self.$message.error(res.msg)
          }
          if (res.data.id) {
            // res.data.id
            const params2 = {
              gadgetId: gadgetId,
              type: 'widget',
              id: res.data.id,
              filterJson,
              filterSql: generalConvertJsonToSQL(filterJson)
            }
            this.$interface.reports.putFilterApi(params2).then((res) => {
              if (res.data.code !== 0) {
                return this.$message.error(res.msg)
              }
              if (res.data.data) {
                this.$store.state.isAttendanceSummaryWidget = true
                this.queryModelDefaultSetting.dataInfo.gadgetId = gadgetId
                this.queryModelDefaultSetting.dataInfo.gadgetType = 'gridgadget'
                this.$nextTick(() => {
                  _self.generateLoading = false
                  this.$store.state.isWidget = true
                  this.showQueryModel()
                })
              }
            })
          }
        })
        .catch(() => { })
    },
    getTeamList () {
      var params = {
        datasetKey: '758965fb-3389-4ee1-bc1d-2e3e44e1d06d'
      }
      this.$interface.reports.getDrillThroughDataInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        if (Array.isArray(res.data)) {
          res.data.forEach(item => {
            var obj = {
              teamId: item.team_id,
              teamName: item.team_name
            }
            var res = this.teamList.some(i => i.teamId === obj.teamId)
            if (!res&&obj.teamId) {
              this.teamList.push(obj)
            }
          })
          res.data.forEach(item => {
            var obj = {
              realName: item.real_name,
              memberId: item.member_id,
              teamId: item.team_id
            }
            var res = this.userLists.some(i => i.realName === obj.realName&&i.teamId === obj.teamId&&i.memberId === obj.memberId)
            if (!res) {
              this.userLists.push(obj)
            }
          })
        }
      }).catch(() => {
      })
    },
    rowDataBound (args) {
      // if (args.data['Freight'] < 30) {
      //   args.row.classList.add('below-30')
      // } else if (args.data['Freight'] < 80) {
      //   args.row.classList.add('below-80')
      // } else {
      //   args.row.classList.add('above-80')
      // }
      // || thisStore.state.user.superTenant === 1
      if ((args.data.managerUserId === thisStore.state.user.id || Boolean(this.$hasPermission('sys:attendance:admin'))) && args.data.status === 'Pending approve') {
        args.row.classList.add('deep_color')
      }
    },
    teamChange (e) {
      this.searchForm.userIds = []
      this.dataForm.userIds = []
      var team = this.teamList.find(item => item.teamId === e)
      if (team) {
        this.dataForm.team = team.teamName
      } else {
        this.dataForm.team = ''
      }
      this.query()
    },
    userChange (e) {
      if (e) return false
      if (this.searchForm.userIds) {
        if (Array.isArray(this.searchForm.userIds) && this.searchForm.userIds.length > 1) {
          this.dataForm.userIds = this.searchForm.userIds.join(',')
        } else {
          this.dataForm.userIds = this.searchForm.userIds[0]
        }
        this.query()
      } else {
        this.dataForm.userIds = null
      }
    },
    userItemChange () {
      if (this.searchForm.userIds) {
        if (Array.isArray(this.searchForm.userIds) && this.searchForm.userIds.length > 1) {
          this.dataForm.userIds = this.searchForm.userIds.join(',')
        } else {
          this.dataForm.userIds = this.searchForm.userIds[0]
        }
        this.query()
      } else {
        this.dataForm.userIds = null
      }
    },
    clearItem () {
      this.dataForm.userIds = null
      this.query()
    },
    modifyDataList (dateFrom, dateTo, userId) {
      this.searchForm.logDateModel = [dateFrom, dateTo]
      // this.dataForm.logTimeStart = this.fromatUtcDate(dateFrom) + 'T00:00:00'
      // this.dataForm.logTimeEnd = this.fromatUtcDate(dateTo) + 'T23:59:59'
      this.dataForm.logTimeStart = moment.tz((moment(dateFrom).format('YYYY-MM-DD') + 'T00:00:00'), this.$store.state.user.timezoneId).utc().format()
      this.dataForm.logTimeEnd = moment.tz((moment(dateTo).format('YYYY-MM-DD') + 'T23:59:59'), this.$store.state.user.timezoneId).utc().format()

      this.searchForm.userIds[0] = userId
      this.$nextTick(() => {
        setTimeout(() => {
          this.userChange()
        }, 800)
      })
    },
    dateChange () {
      if (this.searchForm.logDateModel) {
        // this.dataForm.logTimeStart = this.fromatUtcDate(this.searchForm.logDateModel[0]) + 'T00:00:00'
        // this.dataForm.logTimeEnd = this.fromatUtcDate(this.searchForm.logDateModel[1]) + 'T23:59:59'
        this.dataForm.logTimeStart = moment.tz((moment(this.searchForm.logDateModel[0]).format('YYYY-MM-DD') + 'T00:00:00'), this.$store.state.user.timezoneId).utc().format()
        this.dataForm.logTimeEnd = moment.tz((moment(this.searchForm.logDateModel[1]).format('YYYY-MM-DD') + 'T23:59:59'), this.$store.state.user.timezoneId).utc().format()
      } else {
        this.dataForm.logTimeStart = null
        this.dataForm.logTimeEnd = null
      }
      this.query()
    },
    fromatUtcDate (date) {
      return moment.tz((moment(date).format('YYYY-MM-DD')), this.$store.state.user.timezoneId).utc().format('YYYY-MM-DD')
    },
    getRecordLists (current) {
      return this.query()
    },
    currentChange (e) {
      if (e) {
        this.getRecordLists(e)
      }
    },
    sizeChange (e) {
      this.pageOptions.currentPage = 1
      this.pageOptions.pageSize = e
      if (e) {
        this.getRecordLists()
      }
    },
    timeFormatToUTC (time, timezone) {
      if (time) {
        if (timezone) {
          let localTime = moment(time).tz(moment.tz.guess()).format('YYYY-MM-DD HH:mm:ss')
          let userTime = moment.tz(localTime, timezone).format()
          let lastTime = moment(userTime).utc().format()
          return lastTime
        } else {
          return moment(time).format('YYYY-MM-DD HH:mm:ss')
        }
      }
    },
    async getFormData () {
      const params = { current: 1, size: 1, desc: 'create_time', formCode: config.AttendanceOptionsId }
      const { data: res } = await this.$interface.reports.getFormDataListApi(params);
      if (res.data.records.length > 0) {
        if (res.data.records[0].id) {
          this.dict={...res.data.records[0].dataContent,id:res.data.records[0].id}
        }
      }
      
    },
    async getAdminUser () {
      const { data: response } = await fetchWorkScheduledUser({
        status: 1,
      })
      if (response.code !== 0) {
        throw response.msg
      }
      let adminUser = response.data.find(v => Array.isArray(v.roleList) && v.roleList.includes('Admin'))
      this.adminUserId=adminUser && adminUser.id
    },
  },
  destroyed () {
    BridgeComponentForAttendance.$on('initRecordList')
  }

}
</script>
<style lang="scss" scoped>
.record-content {
  // border: 1px solid palevioletred;
  width: 100%;
  height: 100%;
}
::v-deep tbody .deep_color {
  background-color: #fef0f0 !important;
}
</style>
